import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册' }
  },
  // 普通用户路由
  {
    path: '/user',
    component: () => import('@/layouts/UserLayout.vue'),
    meta: { requiresAuth: true, role: 'user' },
    children: [
      {
        path: '',
        redirect: '/user/dishes'
      },
      {
        path: 'dishes',
        name: 'UserDishes',
        component: () => import('@/views/user/Dishes.vue'),
        meta: { title: '菜品信息' }
      },
      {
        path: 'dish/:id',
        name: 'DishDetail',
        component: () => import('@/views/user/DishDetail.vue'),
        meta: { title: '菜品详情' }
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('@/views/user/Cart.vue'),
        meta: { title: '购物车' }
      },
      {
        path: 'pending-orders',
        name: 'PendingOrders',
        component: () => import('@/views/user/PendingOrders.vue'),
        meta: { title: '待支付订单' }
      },
      {
        path: 'orders',
        name: 'UserOrders',
        component: () => import('@/views/user/Orders.vue'),
        meta: { title: '历史订单' }
      },
      {
        path: 'favorites',
        name: 'Favorites',
        component: () => import('@/views/user/Favorites.vue'),
        meta: { title: '我的收藏' }
      },
      {
        path: 'comments',
        name: 'UserComments',
        component: () => import('@/views/user/Comments.vue'),
        meta: { title: '我的评论' }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/user/Profile.vue'),
        meta: { title: '个人信息' }
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: () => import('@/views/user/ChangePassword.vue'),
        meta: { title: '修改密码' }
      }
    ]
  },
  // 管理员路由
  {
    path: '/admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    meta: { requiresAuth: true, role: 'admin' },
    children: [
      {
        path: '',
        redirect: '/admin/dishes'
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('@/views/admin/Users.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'dishes',
        name: 'AdminDishes',
        component: () => import('@/views/admin/Dishes.vue'),
        meta: { title: '菜品管理' }
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('@/views/admin/Orders.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'comments',
        name: 'AdminComments',
        component: () => import('@/views/admin/Comments.vue'),
        meta: { title: '评论管理' }
      },
      {
        path: 'profile',
        name: 'AdminProfile',
        component: () => import('@/views/admin/Profile.vue'),
        meta: { title: '个人信息' }
      }
    ]
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, _from, next) => {
  const userStore = useUserStore();
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 餐厅管理系统`;
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录');
      next('/login');
      return;
    }

    // 检查账号状态（如果已登录但账号被禁用，强制退出）
    if (userStore.user && userStore.user.status === '1') {
      ElMessage.error('账号已被禁用，请重新登录');
      userStore.logout();
      next('/login');
      return;
    }

    // 检查角色权限
    if (to.meta.role === 'admin' && !userStore.isAdmin) {
      ElMessage.error('无权访问管理员页面');
      next('/user/dishes');
      return;
    }
  }

  // 已登录用户访问登录页，重定向到对应首页
  if ((to.path === '/login' || to.path === '/register') && userStore.isLoggedIn) {
    if (userStore.isAdmin) {
      next('/admin/dishes');
    } else {
      next('/user/dishes');
    }
    return;
  }

  next();
});

export default router;

